package com.klm.easymq.demo.controller;

import com.klm.easymq.demo.entity.Inventory;
import com.klm.easymq.demo.entity.Order;
import com.klm.easymq.demo.service.InventoryService;
import com.klm.easymq.demo.service.NotificationService;
import com.klm.easymq.demo.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 演示控制器
 * 提供REST API接口，演示Easy-MQ SDK的功能
 */
@Slf4j
@RestController
@RequestMapping("/api/demo")
@RequiredArgsConstructor
public class DemoController {
    
    private final OrderService orderService;
    private final InventoryService inventoryService;
    private final NotificationService notificationService;
    
    /**
     * 创建订单
     */
    @PostMapping("/orders")
    public Map<String, Object> createOrder(@RequestBody Map<String, Object> request) {
        try {
            String userId = (String) request.get("userId");
            String productId = (String) request.get("productId");
            String productName = (String) request.get("productName");
            BigDecimal amount = new BigDecimal(request.get("amount").toString());
            
            Order order = orderService.createOrder(userId, productId, productName, amount);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "订单创建成功");
            response.put("order", order);
            
            return response;
            
        } catch (Exception e) {
            log.error("创建订单失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "创建订单失败: " + e.getMessage());
            return response;
        }
    }
    
    /**
     * 更新订单状态
     */
    @PutMapping("/orders/{orderId}/status")
    public Map<String, Object> updateOrderStatus(
            @PathVariable String orderId,
            @RequestBody Map<String, Object> request) {
        try {
            String status = (String) request.get("status");
            Order order = orderService.updateOrderStatus(orderId, status);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "订单状态更新成功");
            response.put("order", order);
            
            return response;
            
        } catch (Exception e) {
            log.error("更新订单状态失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新订单状态失败: " + e.getMessage());
            return response;
        }
    }
    
    /**
     * 取消订单
     */
    @DeleteMapping("/orders/{orderId}")
    public Map<String, Object> cancelOrder(
            @PathVariable String orderId,
            @RequestBody Map<String, Object> request) {
        try {
            String reason = (String) request.get("reason");
            Order order = orderService.cancelOrder(orderId, reason);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "订单取消成功");
            response.put("order", order);
            
            return response;
            
        } catch (Exception e) {
            log.error("取消订单失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "取消订单失败: " + e.getMessage());
            return response;
        }
    }
    
    /**
     * 获取库存信息
     */
    @GetMapping("/inventory")
    public Map<String, Object> getInventory() {
        try {
            ConcurrentHashMap<String, Inventory> inventoryMap = inventoryService.getAllInventory();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("inventory", inventoryMap);
            response.put("total", inventoryMap.size());
            
            return response;
            
        } catch (Exception e) {
            log.error("获取库存信息失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取库存信息失败: " + e.getMessage());
            return response;
        }
    }
    
    /**
     * 获取特定商品库存
     */
    @GetMapping("/inventory/{productId}")
    public Map<String, Object> getInventoryByProductId(@PathVariable String productId) {
        try {
            Inventory inventory = inventoryService.getInventory(productId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("inventory", inventory);
            
            return response;
            
        } catch (Exception e) {
            log.error("获取商品库存失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取商品库存失败: " + e.getMessage());
            return response;
        }
    }
    
    /**
     * 获取统计信息
     */
    @GetMapping("/stats")
    public Map<String, Object> getStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            stats.put("inventoryProcessedCount", inventoryService.getProcessedCount());
            stats.put("notificationCount", notificationService.getNotificationCount());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("stats", stats);
            
            return response;
            
        } catch (Exception e) {
            log.error("获取统计信息失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取统计信息失败: " + e.getMessage());
            return response;
        }
    }
    
    /**
     * 批量创建订单（用于压力测试）
     */
    @PostMapping("/orders/batch")
    public Map<String, Object> batchCreateOrders(@RequestBody Map<String, Object> request) {
        try {
            int count = (Integer) request.get("count");
            String userId = (String) request.get("userId");
            String productId = (String) request.get("productId");
            String productName = (String) request.get("productName");
            BigDecimal amount = new BigDecimal(request.get("amount").toString());
            
            Map<String, Object> results = new HashMap<>();
            int successCount = 0;
            int failCount = 0;
            
            for (int i = 0; i < count; i++) {
                try {
                    Order order = orderService.createOrder(userId, productId, productName, amount);
                    results.put("order_" + i, order);
                    successCount++;
                } catch (Exception e) {
                    log.error("批量创建订单失败: index={}", i, e);
                    failCount++;
                }
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", String.format("批量创建完成: 成功%d个, 失败%d个", successCount, failCount));
            response.put("totalCount", count);
            response.put("successCount", successCount);
            response.put("failCount", failCount);
            response.put("results", results);
            
            return response;
            
        } catch (Exception e) {
            log.error("批量创建订单失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "批量创建订单失败: " + e.getMessage());
            return response;
        }
    }
} 